# -*- coding: UTF-8 -*-
import requests
import cookielib
from bs4 import BeautifulSoup
import simplejson as json
from util import mqUtil
from util import uploadUtil
from util import stringUtil

session=requests.session();
session.proxies={"http://127.0.0.1:8888"}
session.cookies=cookielib.LWPCookieJar(filename="cookies")
try:
    session.cookies.load(ignore_discard=True)
except:
    print "loan cookies fail"
    
headers={}
headers['User-Agent']="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"
headers['Accept-Language']="zh-CN,zh;q=0.8"
headers['Accept-Encoding']='gzip, deflate, sdch'
headers['Accept']="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"

prefix_url="http://my.chsi.com.cn"

###获取登录所需详情参数
def getLoginForm(username, password):    
    mainpage="https://account.chsi.com.cn/passport/login?service=http%3A%2F%2Fmy.chsi.com.cn%2Farchive%2Fj_spring_cas_security_check"
    r=session.get(mainpage, headers=headers, verify=False, allow_redirects=False)
    doc=r.text
    bsoup=BeautifulSoup(doc, "html.parser")
    loginParam={}
    loginParam['lt']=bsoup.find("input", {"name":"lt"})['value']
    loginParam['_eventId']=bsoup.find("input", {"name":"_eventId"})['value']
    loginParam['submit']=bsoup.find("input", {'name':'submit'})['value'].encode("utf-8")
    loginParam['username']=username
    loginParam['password']=password
    return loginParam
   
###登录成功与否 
def doLogin(loginData):
    loginurl="https://account.chsi.com.cn/passport/login?service=http%3A%2F%2Fmy.chsi.com.cn%2Farchive%2Fj_spring_cas_security_check"
    r=session.post(loginurl, data=loginData, headers=headers, verify=False, allow_redirects=True)
    if r.status_code==200:
        infopage=r.text
        isoup=BeautifulSoup(infopage, "html.parser")
        a=isoup.find("a", text=['学籍信息(图像校对)'])['href']
        return True, prefix_url + a
    else:
        print "登录失败"
        return False
 
##下载学籍照片上传到七牛  
def downloadImg(url):
    photo=session.get("http://my.chsi.com.cn"+url, headers=headers)
    with open("img.jpg", "wb") as code:
        code.write(photo.content)
        uploadUrl=uploadUtil.upload("img.jpg")
    code.close()
    return uploadUrl
   
##解析所需信息
def anay(text):
    return text[text.index("\", \"")+4 : len(text)-2]

  
##获取学籍信息
def getInfo(url):
        inf=session.get(url, headers=headers)
        xjxl=inf.text
        xsoup=BeautifulSoup(xjxl, "html.parser")
        scripts=xsoup.findAll("script", {"type":"text/javascript"})
        dataObj={}
        infos=scripts[14].text.split(";")
        ##infos[1]学校信息
        dataObj["school"]=anay(infos[1])
        ##infos[2]专业信息
        dataObj["major"]=anay(infos[2])
        ##infos[3]考生信息
        dataObj["examinee"]=anay(infos[3])
        ##infos[4]学号
        dataObj["studentno"]=anay(infos[4])
        ##infos[5]学历
        dataObj["degree"]=anay(infos[5])
        ##infos[6]级别
        dataObj["level"]=anay(infos[6])
        ##infos[7]学制
        dataObj["system"]=anay(infos[7])
        ##infos[8]身份证
        dataObj["idcard"]=anay(infos[8])
        table=xsoup.find("div", {"id": "resultTable"})
        imgs = table.find_all("img")
        dataObj['img1']=downloadImg(imgs[0].attrs['src']);
        dataObj['img2']=downloadImg(imgs[1].attrs['src']);
        tds=table.findAll("td");
        dataObj['name']=tds[0].text
        dataObj['sex']=tds[2].text
        dataObj['nation']=tds[3].text
        dataObj['birth']=tds[4].text
        dataObj['department']=tds[10].text
        dataObj['class']=tds[12].text
        dataObj['years']=tds[14].text
        dataObj['enterDate']=tds[17].text
        dataObj['status']=tds[18].text
        dataObj['graduationtime']=tds[19].text.replace("\r\n", "").strip()
        print json.dumps(dataObj).decode('unicode_escape')
        mqUtil.publish(stringUtil.gets(json.dumps(dataObj)))
        
#处理
loginData=getLoginForm("1002318371@163.com", "yanghui123")
r, t=doLogin(loginData)
if r == True:
    getInfo(t)
